from PyQt4 import QtCore, QtGui,  QtXml
from PhotoConfig import PhotoConfig
import os.path
import math

def valueOf(data):
    if data.find(".") != -1:
        return float(data)
    else:
        return int(data)


class ConfigLoader():
    def __init__(self,  file):
        self.configs = list()
        self.file = file
        self.ReadConfigFile()
    
    def ReadConfigFile(self):
        dom=QtXml.QDomDocument()
        error=None
        fh=None
        try:
            fh=QtCore.QFile(self.file)
            if not fh.open(QtCore.QIODevice.ReadOnly):
                raise IOError,unicode(fh.errorString())
            if not dom.setContent(fh):
                raise ValueError,"could not parse XML"
        except(IOError,OSError,ValueError),e:
            error="Failedtoimport:%s"%e
        finally:
            if fh is not None:
                fh.close()
            if error is not None:
                return False,error
        try:
            self.ReadFromDOM(dom)
        except ValueError,e:
            return False,"Failed to import:%s" %e
        return True, "Success"     

    def ReadFromDOM(self,dom):
        root=dom.documentElement()
        if root.tagName()!="photo":
            raise ValueError,"not a photo configuration XML file"
        node=root.firstChild()
        while not node.isNull():
            if node.toElement().tagName()=="config":
                self.c_cfg = PhotoConfig()
                self.ReadConfigNode(node.toElement())
                self.configs.append(self.c_cfg)
            node=node.nextSibling()

    def ReadConfigNode(self,  element):
        node=element.firstChild()
        while not node.isNull():
            if node.toElement().tagName()=="name":
                self.c_cfg.SetName(self.GetText(node))
            elif node.toElement().tagName()=="format":
                self.c_cfg.SetFormat(self.GetText(node))
            elif node.toElement().tagName()=="size":
                self.ReadSizeNode(node.toElement())
            node=node.nextSibling()        
        
    def ReadSizeNode(self,  element):
        node=element.firstChild()
        while not node.isNull():
            if node.toElement().tagName()=="unit":
                self.c_cfg.SetUnit(self.GetText(node))
            elif node.toElement().tagName()=="dpi":
                self.c_cfg.SetDpi(valueOf(self.GetText(node)))
            elif node.toElement().tagName()=="width":
                self.c_cfg.SetWidth(valueOf(self.GetText(node)))
            elif node.toElement().tagName()=="height":
                self.c_cfg.SetHeight(valueOf(self.GetText(node)))
            elif node.toElement().tagName()=="head2chin":
                self.ReadH2CNode(node.toElement())
            node=node.nextSibling()  
    
    def ReadH2CNode(self,  element):
        node=element.firstChild()
        while not node.isNull():
            if node.toElement().tagName()=="min":
                self.c_cfg.SetH2CMin(valueOf(self.GetText(node)))
            elif node.toElement().tagName()=="max":
                self.c_cfg.SetH2CMax(valueOf(self.GetText(node)))
            node=node.nextSibling() 

    def GetText(self, node):
        child=node.firstChild()
        text=QtCore.QString()
        while not child.isNull():
            if child.nodeType()==QtXml.QDomNode.TextNode:
                text+=child.toText().data()
            child=child.nextSibling()
        return str(text.trimmed())
        
    def GetConfigs(self):
        return self.configs
        

if __name__ == "__main__":
    cfg = ConfigLoader("./config/Singapore.xml")
    print cfg.GetConfigs()
